package com.dragonfly.shutter.controllers;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.dragonfly.shutter.DAOs.AdminDAO;
import com.dragonfly.shutter.beans.Admin;
import com.dragonfly.shutter.utils.MD5Util;
import com.dragonfly.shutter.validator.AdminLoginValidator;

/**
 * 管理员登录控制器，用于控制管理员的登录流程
 * @author 赵洁琼
 *
 */
@Controller
@SessionAttributes("validateCode")
public class AdminLoginController {
	@Autowired
	private AdminDAO adminDAO;
	@Autowired
	private AdminLoginValidator adminLoginValidator;
	
	/**
	 * 初始化管理员登录页面
	 * @param model 初始化页面中的绑定对象管理员（admin）
	 * @return 管理员登录页面的模版名称
	 */
	@RequestMapping(value = "/adminLogin.html", method = RequestMethod.GET)
	public String setupAdminLoginForm(ModelMap model){
		Admin admin = new Admin();
		model.addAttribute("admin", admin);
		return "adminLogin";		
	}
	
	/**
	 * 管理员登录页面流程
	 * @param admin
	 * @param result
	 * @param validateCode
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/adminLogin.html", method = RequestMethod.POST)
	public ModelAndView adminLogin(@ModelAttribute("admin") Admin admin, BindingResult result,
			@ModelAttribute("validateCode") String validateCode,HttpSession session)
	{
		//验证码是否正确
		if(!validateCode.equals(admin.getValidateCode().toUpperCase())){
			result.rejectValue("validateCode", "validator.error", "验证码不正确");
			return new ModelAndView("adminLogin");
		}
		
		//验证管理员的邮箱和密码是否符合格式上的要求
		adminLoginValidator.validate(admin, result);
		if(result.hasErrors()){
			return new ModelAndView("adminLogin");
		}
		
		String passwd = MD5Util.EncoderByMd5(admin.getAdminPassword().getBytes());
		admin.setAdminPassword(passwd);
		
		admin = adminDAO.selectAdminByEmailAndPassword(admin);
		
		//验证管理员的登录信息
		if(admin == null||
				!admin.getAdminPermission().equalsIgnoreCase("yes")){
			return new ModelAndView("adminLogin");
		}
		
		//将管理员id放入到session中
		session.setAttribute("adminID", admin.getAdminID());
		
		return new ModelAndView("redirect:/admin.html");		
	}
	
}
